/**
 *
 */
package org.insia.smartposse.manager.list;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.hibernate.Session;
import org.insia.smartposse.form.SearchJobsForm;
import org.insia.smartposse.manager.JobProjectManager;
import org.insia.smartposse.manager.ProjectManager;
import org.insia.smartposse.manager.SkillManager;
import org.insia.smartposse.mapping.JobProject;
import org.insia.smartposse.mapping.dao.JobProjectDAO;

/**
 * Manage a list of Job
 *
 * @author cmougel
 *
 */
public final class JobsListManager extends ArrayList {

	public static int NOTCOMPLETE = 0;
	public static int COMPLETE = 1;
	public static int ALL = 2;

	private List<JobProject> _jobs = new ArrayList<JobProject>();
	private final JobProjectDAO _dao = new JobProjectDAO();
	private final Session _session;
	private Boolean _search = false;
	private int _complete = 2;
	private ProjectManager _project = null;
	private SkillManager _skill = null;

	/**
	 * Get All Project
	 *
	 */
	@SuppressWarnings("unchecked")
	public JobsListManager(){
		_session = _dao.getSession();
	}

	/**
	 * Constructeur with a boolean if you want only job complete or not
	 *
	 * @param complete
	 */
	public JobsListManager(int complete){
		this();
		_complete = complete;
	}

	public JobsListManager(Set<JobProject> jobs){
		this();
		_jobs = new ArrayList<JobProject>(jobs);
		_search = true;
	}

	public JobsListManager(SearchJobsForm searchForm) {
		this();

		if (0 < searchForm.getSkill()){
			setSkill(new SkillManager(searchForm.getSkill()));
		}

		setComplete(searchForm.getComplete());
	}

	public void setProject(ProjectManager project){
		_project  = project;
		_search = false;
	}

	public void search(){
		if (!_search){
			_jobs = _dao.search(_session, _complete, _project, _skill);
		}
	}
	/**
	 * Destruct and close the session
	 */
	public void finalize(){
		JobProjectDAO.closeCurrentSession();
	}

	@Override
	public JobProjectManager get(int index) {
		search();
		return new JobProjectManager(_jobs.get(index));
	}

	@Override
	public int size() {
		search();
		return _jobs.size();
	}

	public void setComplete(int complete) {
		_complete = complete;
		_search = false;
	}

	public void setSkill(SkillManager skill){
		_skill = skill;
		_search = false;
	}
}
